<template>
  <el-card>
    <el-form inline class="cartgroy-select-form">
      <el-form-item label="一级分类">
        <!-- 
                  必须绑定v-model收集数据，才能选中值
             -->
        <el-select placeholder="请选择" v-model="cartgroy1Id">
          <!-- 
            label  显示的内容
            value  选中的值
          -->
          <el-option
            v-for="item in cartgroy1List"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select placeholder="请选择" v-model="cartgroy2Id">
          <el-option
            v-for="item in cartgroy2List"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            ref="cartgroy2"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择" v-model="cartgroy3Id">
          <el-option
            v-for="item in cartgroy3List"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            ref="cartgroy3"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CartgroySelect",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import {
  getCartgroy1ListApi,
  getCartgroy2ListApi,
  getCartgroy3ListApi,
} from "@/api/product/cartgroyselect";

import type { categoryList } from "@/api/product/model/cartgroyselectModel";

onMounted(async () => {
  let result = await getCartgroy1ListApi();
  cartgroy1List.value = result;
});

const cartgroy1List = ref<categoryList>([]);
const cartgroy2List = ref<categoryList>([]);
const cartgroy3List = ref<categoryList>([]);

const cartgroy1Id = ref<undefined | number>();
const cartgroy2Id = ref<undefined | number>();
const cartgroy3Id = ref<undefined | number>();

const cartgroy2 = ref();
const cartgroy3 = ref();

/******************************* 请求分类数据展示列表 **********************************/
// 监视1级分类Id
// 当一级分类选择后请求二级分类数据
watch(cartgroy1Id, async (newVal) => {
  let result = await getCartgroy2ListApi(newVal as number);
  cartgroy2List.value = result;
  cartgroy2Id.value = undefined;
  cartgroy3Id.value = undefined;
  cartgroy3List.value = [];
  //   console.log(result);
});

// 监视二级分类Id
// 当二级分类选择后请求三级分类数据
watch(cartgroy2Id, async (newVal) => {
  if (!newVal) return;
  let result = await getCartgroy3ListApi(newVal as number);
  cartgroy3List.value = result;
  cartgroy3Id.value = undefined;
  //   console.log(result);
});
</script>

<style scoped>
.cartgroy-select-form :deep(.el-form-item) {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
